#pragma once
#include <functional>
#include <signal.h>
#include "log.hpp"
#include "Socket.hpp"
#include "ServerCal.hpp"
#include "Protocal.hpp"

using func_t=function<string(string&)>;
extern Log lg;

class Server
{
public:
    Server(uint16_t port,func_t calback):port_(port) ,calback_(calback)
    {}

    bool Init()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
        lg("info","init server .... done");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while(true)
        {
            string clientip;
            uint16_t clientport;

            int sockfd=listensock_.Accpect(&clientip,&clientport);
            if(sockfd<0)
            {
                lg("fatal","accpect fail");
                break;
            }
            
            lg("info","accpect success");
            if(fork()==0)
            {
                listensock_.Close();
                string inbuffer_stream;
                while(true)
                {
                    char buffer[1024];
                    int n=read(sockfd,buffer,sizeof(buffer));
                    if(n>0)
                    {
                        buffer[n]=0;
                        inbuffer_stream+=buffer;
                        lg("Debug", "debug:\n%s", inbuffer_stream.c_str());

                        while(true)
                        {
                            string ret=calback_(inbuffer_stream);
                            if(ret.empty())
                            break;

                            lg("Dedug","debug:\n%s",ret.c_str());
                            lg("Dedug","debug:\n%s",inbuffer_stream.c_str());

                            write(sockfd,ret.c_str(),ret.size());
                        }
                    }
                    else 
                    {
                        cout<<"错误了"<<endl;
                        break;
                    }
                }
                exit(0);
            }
            close(sockfd);
        }
    }

private:
    Sock listensock_;
    uint16_t port_;
    func_t calback_;
};